<script setup lang="ts">
import { useMemberStore } from '@/stores'
import { http } from '@/utils/http';
import { ref, watch } from 'vue';

// 定义密码和错误信息的响应式变量
const password1 = ref('');
const password2 = ref('');
const errorMessage = ref('');
const rememberedUsername = ref('');
const successMessage = ref('');
const showLocalPageUsername = ref('');

const showUserInfo = () => {
  showLocalPageUsername.value = uni.getStorageSync('rememberedUsername')
};

// 定义检查规则
interface Rule {
  regex: RegExp;
  message: string;
}

const rules: Rule[] = [
  { regex: /[A-Z]/, message: '需要包含大写字母' },
  { regex: /[a-z]/, message: '需要包含小写字母' },
  { regex: /\d/, message: '需要包含数字' },
  { regex: /[\W_]/, message: '需要包含特殊字符' }
];

// 验证密码的方法
const validatePassword = (newPassword: string) => {
  // 清空错误消息
  errorMessage.value = '';

  // 检查密码长度
  if (newPassword.length < 6) {
    errorMessage.value = '密码长度需要不少于6位';
    return false;
  }

  // 计算满足条件的数量
  let count = 0;
  for (let rule of rules) {
    if (rule.regex.test(newPassword)) {
      count++;
    }
  }

  // 判断是否满足至少三种条件
  if (count < 3) {
    errorMessage.value = '密码需要包含大写字母、小写字母、数字和特殊字符中的至少三种';
    return false;
  }

  return true;
};

// 监听password2的变化并验证密码
watch(password2, newPassword => {
  validatePassword(newPassword);
}, { immediate: true }); // 立即执行一次以初始化

// 在失去焦点时调用验证方法
const validatePasswordOnBlur = () => {
  if (!validatePassword(password2.value)) {
    // 如果验证失败，可以在这里添加额外的提醒逻辑，比如聚焦回输入框等。
    // 例如：alert('请确保密码符合要求');
    console.log('密码不符合要求' + errorMessage.value);


  }
};

//点击修改密码时调用验证方法
const doModifyPassword = async () => {
  // 验证密码，如果不符合要求，弹出提示
  if (!validatePassword(password2.value)) {
    uni.showToast({
      title: '您输入的密码不符合要求！',
      icon: 'none',
      duration: 2000
    });
    return;
  }
  rememberedUsername.value = uni.getStorageSync('rememberedUsername');
  //输入的密码符合要求，可以发送请求修改密码
  // 发送修改密码请求
  const res = await http<string[]>({
    method: 'POST',
    url: '/user/modifyPassword',
    data: {
      password1: password1.value,
      password2: password2.value,
      username: rememberedUsername.value
    }
  });
  successMessage.value = '';
  //返回0，用户不存在，返回1，原密码错误，返回2，修改成功
  console.log(res);
  if (res == 0) {
    uni.showToast({
      title: '用户不存在',
      icon: 'error',
      duration: 2000
    });
    return;
  } else if (res == 1) {
    uni.showToast({
      title: '当前密码错误',
      icon: 'error',
      duration: 2000
    });
    return;
  }
  if (res == 2) {
    uni.showToast({
      title: '修改成功！',
      icon: 'success',
      duration: 2000
    });
  }
  //修改成功后清空输入框
  password1.value = '';
  password2.value = '';
  successMessage.value = '密码已修改';

  //5秒后，调用执行退出函数
  setTimeout(() => {
    doLoginOut();
  }, 5000);


};

//执行退出函数
const doLoginOut = () => {
  //跳转回首页
  uni.switchTab({
    url: '/pages/index/index' // 确保此路径是 tabBar 中定义的一个页面
  });

  // 清除本地存储
  uni.removeStorageSync('rememberedUsername');
  uni.removeStorageSync('rememberedPassword');
  uni.removeStorageSync('token');
}


const memberStore = useMemberStore()


</script>

<template>
  <view class="my">
    <view>用户信息：{{ showLocalPageUsername }}</view>
    <view class="myButtons">
      <button @click="showUserInfo" size="mini" plain type="primary">
        显示用户
      </button>
      <button @click="doLoginOut" size="mini" plain type="warn">退出账号</button>
      <button @click="" size="mini" plain type="primary">待开发</button>
    </view>
  </view>
  <view class="login-container">
    <view class="login-form">
      <uni-section>
        <text>当前密码：</text>
      </uni-section>
      <uni-section>
        <uni-easyinput type="password" v-model="password1" placeholder="当前密码" clearable></uni-easyinput>
      </uni-section>
      <!-- <uni-section>
        <uni-easyinput type="password" v-model="password2" placeholder="请要修改的密码" clearable></uni-easyinput>
      </uni-section> -->
      <uni-section>
        <text>密码修改输入：</text>
      </uni-section>
      <uni-section>
        <uni-easyinput type="password" v-model="password2" placeholder="密码修改为" clearable :error-message="errorMessage"
          @blur="validatePasswordOnBlur" />
      </uni-section>
      <uni-section>
        <text style="color: red;">{{ errorMessage }}</text>
      </uni-section>



      <view class="button-container">
        <button @click="doModifyPassword" class="login-button">修改密码</button>
        <!-- <button @click="doRegister" class="register-button">注册</button> -->
      </view>
      <uni-section>
        <text style="color: red;">{{ successMessage }}</text>
      </uni-section>
    </view>
  </view>
</template>
<style lang="scss">
.login-container {
  display: flex;
  justify-content: center;
  // align-items: center;
  align-items: flex-start;
  height: 100vh;
  background-color: #f0f2f5;
}

.login-form {
  display: flex;
  flex-wrap: wrap;
  width: 70%; // 调整宽度，使其更适合移动设备
  max-width: 300px; // 最大宽度
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  text-align: center;
  flex-direction: column;

  margin-top: 5vh;


  .h2 {
    margin-bottom: 20px;
    font-size: 2rem; // 调整标题字体大小
    color: #333;
    align-self: center;
  }

  .input-field {
    width: 100%;
    height: 40px;
    padding: 10px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    font-size: 1rem;
    box-sizing: border-box; // 确保内边距和边框不会增加元素的总宽度
  }

  .checkbox-container {
    display: flex;
    justify-content: space-between;
    margin-bottom: 35px;
    font-size: 0.9rem; // 调整复选框字体大小
  }

  .checkbox-set {
    margin-top: 15px;
  }

  .button-container {
    display: flex;
    flex-wrap: wrap;
  }

  .login-button {
    width: 100px;
    height: 30px;
    padding: 0px;
    background-color: #1890ff;
    color: #fff;
    border: none;
    border-radius: 4px;
    font-size: 1rem;
    cursor: pointer;
    margin-bottom: 15px;
    line-height: 30px;
    margin-top: 15px;

    &:hover {
      background-color: #40a9ff;
    }
  }
}

.myButtons {
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  justify-content: space-evenly;
}
</style>
